import * as Cesium from 'cesium';

export class Entity {
  constructor(cesiumManager) {
    this.cesiumManager = cesiumManager;
  }

  /**
   * 创建点实体
   * @param {String} id - 实体ID
   * @param {Object} position - 位置 {longitude, latitude, height}
   * @param {Object} options - 点选项
   * @returns {Entity} 创建的实体
   */
  createPoint(id, position, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const defaultOptions = {
      pixelSize: 10,
      color: Cesium.Color.RED,
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 1,
      heightReference: Cesium.HeightReference.NONE
    };

    const pointOptions = Object.assign({}, defaultOptions, options);

    const entity = this.cesiumManager.viewer.entities.add({
      id: id,
      name: id,
      position: Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, position.height || 0),
      point: {
        pixelSize: pointOptions.pixelSize,
        color: pointOptions.color,
        outlineColor: pointOptions.outlineColor,
        outlineWidth: pointOptions.outlineWidth,
        heightReference: pointOptions.heightReference
      }
    });

    return entity;
  }

  /**
   * 创建折线实体
   * @param {String} id - 实体ID
   * @param {Array} positions - 位置数组 [{longitude, latitude, height}, ...]
   * @param {Object} options - 折线选项
   * @returns {Entity} 创建的实体
   */
  createPolyline(id, positions, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const defaultOptions = {
      width: 2,
      material: Cesium.Color.RED,
      clampToGround: false
    };

    const polylineOptions = Object.assign({}, defaultOptions, options);

    const cartesianPositions = positions.map(pos => 
      Cesium.Cartesian3.fromDegrees(pos.longitude, pos.latitude, pos.height || 0)
    );

    const entity = this.cesiumManager.viewer.entities.add({
      id: id,
      name: id,
      polyline: {
        positions: cartesianPositions,
        width: polylineOptions.width,
        material: polylineOptions.material,
        clampToGround: polylineOptions.clampToGround
      }
    });

    return entity;
  }

  /**
   * 创建多边形实体
   * @param {String} id - 实体ID
   * @param {Array} positions - 顶点位置数组 [{longitude, latitude, height}, ...]
   * @param {Object} options - 多边形选项
   * @returns {Entity} 创建的实体
   */
  createPolygon(id, positions, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const defaultOptions = {
      material: Cesium.Color.RED.withAlpha(0.5),
      outline: true,
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 1,
      height: 0,
      extrudedHeight: undefined
    };

    const polygonOptions = Object.assign({}, defaultOptions, options);

    const cartesianPositions = positions.map(pos => 
      Cesium.Cartesian3.fromDegrees(pos.longitude, pos.latitude, pos.height || 0)
    );

    const entity = this.cesiumManager.viewer.entities.add({
      id: id,
      name: id,
      polygon: {
        hierarchy: cartesianPositions,
        material: polygonOptions.material,
        outline: polygonOptions.outline,
        outlineColor: polygonOptions.outlineColor,
        outlineWidth: polygonOptions.outlineWidth,
        height: polygonOptions.height,
        extrudedHeight: polygonOptions.extrudedHeight
      }
    });

    return entity;
  }

  /**
   * 创建圆形实体
   * @param {String} id - 实体ID
   * @param {Object} center - 圆心位置 {longitude, latitude, height}
   * @param {Number} radius - 半径（米）
   * @param {Object} options - 圆形选项
   * @returns {Entity} 创建的实体
   */
  createCircle(id, center, radius, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const defaultOptions = {
      material: Cesium.Color.RED.withAlpha(0.5),
      outline: true,
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 1,
      height: 0,
      extrudedHeight: undefined
    };

    const circleOptions = Object.assign({}, defaultOptions, options);

    const entity = this.cesiumManager.viewer.entities.add({
      id: id,
      name: id,
      position: Cesium.Cartesian3.fromDegrees(center.longitude, center.latitude, center.height || 0),
      ellipse: {
        semiMajorAxis: radius,
        semiMinorAxis: radius,
        material: circleOptions.material,
        outline: circleOptions.outline,
        outlineColor: circleOptions.outlineColor,
        outlineWidth: circleOptions.outlineWidth,
        height: circleOptions.height,
        extrudedHeight: circleOptions.extrudedHeight
      }
    });

    return entity;
  }

  /**
   * 创建椭圆实体
   * @param {String} id - 实体ID
   * @param {Object} center - 中心位置 {longitude, latitude, height}
   * @param {Number} semiMajorAxis - 长半轴
   * @param {Number} semiMinorAxis - 短半轴
   * @param {Object} options - 椭圆选项
   * @returns {Entity} 创建的实体
   */
  createEllipse(id, center, semiMajorAxis, semiMinorAxis, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const defaultOptions = {
      material: Cesium.Color.RED.withAlpha(0.5),
      outline: true,
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 1,
      height: 0,
      extrudedHeight: undefined,
      rotation: 0
    };

    const ellipseOptions = Object.assign({}, defaultOptions, options);

    const entity = this.cesiumManager.viewer.entities.add({
      id: id,
      name: id,
      position: Cesium.Cartesian3.fromDegrees(center.longitude, center.latitude, center.height || 0),
      ellipse: {
        semiMajorAxis: semiMajorAxis,
        semiMinorAxis: semiMinorAxis,
        rotation: ellipseOptions.rotation,
        material: ellipseOptions.material,
        outline: ellipseOptions.outline,
        outlineColor: ellipseOptions.outlineColor,
        outlineWidth: ellipseOptions.outlineWidth,
        height: ellipseOptions.height,
        extrudedHeight: ellipseOptions.extrudedHeight
      }
    });

    return entity;
  }

  /**
   * 创建矩形实体
   * @param {String} id - 实体ID
   * @param {Object} coordinates - 矩形坐标 {west, south, east, north}
   * @param {Object} options - 矩形选项
   * @returns {Entity} 创建的实体
   */
  createRectangle(id, coordinates, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const defaultOptions = {
      material: Cesium.Color.RED.withAlpha(0.5),
      outline: true,
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 1,
      height: 0,
      extrudedHeight: undefined
    };

    const rectangleOptions = Object.assign({}, defaultOptions, options);

    const entity = this.cesiumManager.viewer.entities.add({
      id: id,
      name: id,
      rectangle: {
        coordinates: Cesium.Rectangle.fromDegrees(
          coordinates.west, 
          coordinates.south, 
          coordinates.east, 
          coordinates.north
        ),
        material: rectangleOptions.material,
        outline: rectangleOptions.outline,
        outlineColor: rectangleOptions.outlineColor,
        outlineWidth: rectangleOptions.outlineWidth,
        height: rectangleOptions.height,
        extrudedHeight: rectangleOptions.extrudedHeight
      }
    });

    return entity;
  }

  /**
   * 创建墙体实体
   * @param {String} id - 实体ID
   * @param {Array} positions - 墙体位置数组 [{longitude, latitude, height}, ...]
   * @param {Object} options - 墙体选项
   * @returns {Entity} 创建的实体
   */
  createWall(id, positions, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const defaultOptions = {
      material: Cesium.Color.RED.withAlpha(0.5),
      outline: true,
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 1
    };

    const wallOptions = Object.assign({}, defaultOptions, options);

    const cartesianPositions = positions.map(pos => 
      Cesium.Cartesian3.fromDegrees(pos.longitude, pos.latitude, pos.height || 0)
    );

    const heights = positions.map(pos => pos.height || 0);

    const entity = this.cesiumManager.viewer.entities.add({
      id: id,
      name: id,
      wall: {
        positions: cartesianPositions,
        maximumHeights: heights,
        minimumHeights: new Array(heights.length).fill(0),
        material: wallOptions.material,
        outline: wallOptions.outline,
        outlineColor: wallOptions.outlineColor,
        outlineWidth: wallOptions.outlineWidth
      }
    });

    return entity;
  }

  /**
   * 创建模型实体
   * @param {String} id - 实体ID
   * @param {Object} position - 位置 {longitude, latitude, height}
   * @param {String} modelUrl - 模型URL
   * @param {Object} options - 模型选项
   * @returns {Entity} 创建的实体
   */
  createModel(id, position, modelUrl, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const defaultOptions = {
      scale: 1.0,
      minimumPixelSize: 128,
      maximumScale: 20000,
      color: Cesium.Color.WHITE,
      colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT
    };

    const modelOptions = Object.assign({}, defaultOptions, options);

    const entity = this.cesiumManager.viewer.entities.add({
      id: id,
      name: id,
      position: Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, position.height || 0),
      model: {
        uri: modelUrl,
        scale: modelOptions.scale,
        minimumPixelSize: modelOptions.minimumPixelSize,
        maximumScale: modelOptions.maximumScale,
        color: modelOptions.color,
        colorBlendMode: modelOptions.colorBlendMode
      }
    });

    return entity;
  }

  /**
   * 创建标签实体
   * @param {String} id - 实体ID
   * @param {Object} position - 位置 {longitude, latitude, height}
   * @param {String} text - 标签文本
   * @param {Object} options - 标签选项
   * @returns {Entity} 创建的实体
   */
  createLabel(id, position, text, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const defaultOptions = {
      font: '14px sans-serif',
      fillColor: Cesium.Color.WHITE,
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 2,
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      pixelOffset: new Cesium.Cartesian2(0.0, -30),
      heightReference: Cesium.HeightReference.NONE
    };

    const labelOptions = Object.assign({}, defaultOptions, options);

    const entity = this.cesiumManager.viewer.entities.add({
      id: id,
      name: id,
      position: Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, position.height || 0),
      label: {
        text: text,
        font: labelOptions.font,
        fillColor: labelOptions.fillColor,
        outlineColor: labelOptions.outlineColor,
        outlineWidth: labelOptions.outlineWidth,
        style: labelOptions.style,
        pixelOffset: labelOptions.pixelOffset,
        heightReference: labelOptions.heightReference
      }
    });

    return entity;
  }

  /**
   * 创建布告板实体
   * @param {String} id - 实体ID
   * @param {Object} position - 位置 {longitude, latitude, height}
   * @param {String} image - 图像URL
   * @param {Object} options - 布告板选项
   * @returns {Entity} 创建的实体
   */
  createBillboard(id, position, image, options = {}) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const defaultOptions = {
      scale: 1.0,
      color: Cesium.Color.WHITE,
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      heightReference: Cesium.HeightReference.NONE,
      pixelOffset: new Cesium.Cartesian2(0, 0)
    };

    const billboardOptions = Object.assign({}, defaultOptions, options);

    const entity = this.cesiumManager.viewer.entities.add({
      id: id,
      name: id,
      position: Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, position.height || 0),
      billboard: {
        image: image,
        scale: billboardOptions.scale,
        color: billboardOptions.color,
        horizontalOrigin: billboardOptions.horizontalOrigin,
        verticalOrigin: billboardOptions.verticalOrigin,
        heightReference: billboardOptions.heightReference,
        pixelOffset: billboardOptions.pixelOffset
      }
    });

    return entity;
  }

  /**
   * 更新实体属性
   * @param {String} id - 实体ID
   * @param {Object} options - 更新选项
   */
  updateEntity(id, options) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    const entity = this.cesiumManager.viewer.entities.getById(id);
    if (!entity) {
      throw new Error(`Entity with id "${id}" not found`);
    }

    // 更新位置
    if (options.position) {
      entity.position = Cesium.Cartesian3.fromDegrees(
        options.position.longitude, 
        options.position.latitude, 
        options.position.height || 0
      );
    }

    // 更新点属性
    if (options.point && entity.point) {
      Object.assign(entity.point, options.point);
    }

    // 更新折线属性
    if (options.polyline && entity.polyline) {
      Object.assign(entity.polyline, options.polyline);
    }

    // 更新多边形属性
    if (options.polygon && entity.polygon) {
      Object.assign(entity.polygon, options.polygon);
    }

    // 更新椭圆/圆形属性
    if (options.ellipse && entity.ellipse) {
      Object.assign(entity.ellipse, options.ellipse);
    }

    // 更新矩形属性
    if (options.rectangle && entity.rectangle) {
      Object.assign(entity.rectangle, options.rectangle);
    }

    // 更新墙体属性
    if (options.wall && entity.wall) {
      Object.assign(entity.wall, options.wall);
    }

    // 更新模型属性
    if (options.model && entity.model) {
      Object.assign(entity.model, options.model);
    }

    // 更新标签属性
    if (options.label && entity.label) {
      Object.assign(entity.label, options.label);
    }

    // 更新布告板属性
    if (options.billboard && entity.billboard) {
      Object.assign(entity.billboard, options.billboard);
    }
  }

  /**
   * 删除实体
   * @param {String} id - 实体ID
   */
  removeEntity(id) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    this.cesiumManager.viewer.entities.removeById(id);
  }

  /**
   * 获取实体
   * @param {String} id - 实体ID
   * @returns {Entity} 实体对象
   */
  getEntity(id) {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    return this.cesiumManager.viewer.entities.getById(id);
  }

  /**
   * 获取所有实体
   * @returns {EntityCollection} 实体集合
   */
  getAllEntities() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    return this.cesiumManager.viewer.entities;
  }

  /**
   * 清除所有实体
   */
  clearAllEntities() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) {
      throw new Error('Cesium manager or viewer is not initialized');
    }

    this.cesiumManager.viewer.entities.removeAll();
  }
}